<?php
/**
 * A simple description for this script
 *
 * PHP Version 5.2.0 or Upper version
 *
 * @package    Paylog
 * @author     Hidehito NOZAWA aka Suin <http://suin.asia>
 * @copyright  2010 Hidehito NOZAWA
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU GPL v2
 *
 */

class Paylog_Controller_DeleteBalance extends Paylog_Abstract_Controller
{
	protected $balanceHand = null;
	protected $balanceObj  = null;
	protected $balanceId   = null;

	protected $errors   = array();

	public function __construct()
	{
		parent::__construct();
		$this->balanceHand = new Paylog_Object_BalanceHandler;
		$this->balanceId   = Paylog::get('balance_id');

		$this->balanceObj  = $this->balanceHand->load($this->balanceId);

		$this->output['errors'] =& $this->errors;
	}

	public function main()
	{
		$this->_validateAccess();

		try
		{
			if ( Paylog::post('delete') )
			{
				$this->_delete();
			}
		}
		catch(Exception $e)
		{
		}
		
		$this->_default();
	}

	protected function _validateAccess()
	{
		if ( !Paylog::$cms->isUser() )
		{
			Paylog::redirect("Please login");
		}

		if ( Paylog::$cms->userId != $this->balanceObj->getVar('uid') )
		{
			Paylog::redirect("Only owner can edit.");
		}
	}

	protected function _default()
	{
		$this->output['token']  = Paylog_Class_Ticket::issue();

		$this->output['balance'] = array(
			'id'   => $this->balanceObj->getVar('id'),
			'name' => $this->balanceObj->getVar('name'),
		);

		$this->_view();
	}

	protected function _delete()
	{
		$this->_validateInput();

		if ( !$this->balanceHand->delete($this->balanceId) )
		{
			$this->_addError("Item deleting failed.");
			$this->_riseError();
		}

		$relBalanceTagHand = new Paylog_Object_RelBalanceTagHandler;

		if ( !$relBalanceTagHand->deleteByBalanceId($this->balanceId) )
		{
			$this->_addError("Could not unlink balance and tag.");
		}

		$date = $this->balanceObj->getVar('date');
		$date = date('Y-m-d', $date);
		$params = array(
			'book_id' => $this->balanceObj->getVar('book_id'),
			'start'   => $date,
			'end'     => $date,
		);

		Paylog::redirect("Item successly deleted.", null, 'detail', null, $params);
	}

	protected function _validateInput()
	{
		$token = Paylog::post('token');
		if ( !Paylog_Class_Ticket::check($token) )
		{
			$this->_addError("Ticket Error");
		}

		if ( count($this->errors) > 0 )
		{
			$this->_riseError();
		}
	}

	protected function _addError($msg)
	{
		$this->errors[] = Paylog::msg($msg);
	}

	protected function _riseError()
	{
		throw new Exception();
	}
}

?>
